'''Generic object pickler and compressor

This module saves and reloads compressed representations of generic Python
objects to and from the disk.
'''

__author__ = "Bill McNeill <billmcn@speakeasy.net>"
__version__ = "1.0"

'''
From:
    http://code.activestate.com/recipes/189972-zip-and-pickle/

Notes:
    Licensed under the PSF License
    Viewed 3236 times
    Revision 2 (updated 8 years ago)
'''

import pickle
import gzip

def save(object, filename, protocol=1):
    '''Saves a compressed object to disk
    '''
    with gzip.GzipFile(filename, 'wb') as file:
        file.write(pickle.dumps(object, protocol))

def load(filename):
    '''Loads a compressed object from disk
    '''
    with gzip.GzipFile(filename, 'rb') as file:
        data = file.read()
        object = pickle.loads(data)

    return object
    
if __name__ == "__main__":
    import sys
    import os.path
    
    class Object:
        x = 7
        y = "This is an object."
    
    filename = sys.argv[1]
    if os.path.isfile(filename):
        o = load(filename)
        print "Loaded %s" % o
    else:
        o = Object()
        save(o, filename)
        print "Saved %s" % o
